#include "client.h"

int	main(int argc, char **argv)
{
  int res = 0;
  int port = 0;
  char *addr = NULL;

  if (argc < 3)
    printf("Arguments missing !\n");
  else
    {
      port = atoi(argv[1]);
      addr = argv[2];
      res = init_socket(port, addr);
      /*if ( res == -1)
	printf("Connection error !\n");
      else
      ip_request(res, port, addr);*/
    }

  return 0;
}

int	init_socket(int port, char *addr)
{
  int			sfd;
  int			len;
  unsigned char		ttl = 1;
  struct sockaddr_in	ssock;
  char			*msg = NULL;
  char			buf[1024] = {0};

  sfd = socket(PF_INET, SOCK_DGRAM, 0);

  if (sfd < 0)
    {
      perror("socket");
      return -1;
    }

  msg = malloc(20 * sizeof(char));
  msg = strcat(msg, "20");
  msg = strcat(msg, get_ip());
  msg = strcat(msg, "\n");
  memset(&ssock, 0, sizeof(ssock));
  ssock.sin_family = AF_INET;
  ssock.sin_port = htons(port);
  ssock.sin_addr.s_addr = inet_addr(addr);

  len = sizeof(ssock);

  if (setsockopt(sfd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)) == -1)
    {
      perror("setsockopt");
      return -1;
    }

  if (sendto(sfd, msg, strlen(msg), 0, (struct sockaddr*) &ssock, sizeof(ssock)) < 0)
    {
      perror("sendto1");
      return -1;
    }

  if (recvfrom(sfd, buf, 1024, 0, (struct sockaddr *) &ssock, &len) < 0)
    {
      perror("recvfrom error");
      return -1;
    }

  printf(buf);

  return sfd;
}

int	ip_request(int  sfd,int  port,char *addr)
{
  char	*msg;
  struct sockaddr_in ssock;
  int	res = 0;
  char			buff[BUFFSIZE] = {0};
  int			len = 0;

  len = sizeof(ssock);
  msg = malloc (18 * sizeof(char));
  msg = strcat(msg, "20");
  msg = strcat(msg, (char *)get_ip());

  memset(&ssock, 0, sizeof(ssock));
  ssock.sin_family = AF_INET;
  ssock.sin_port = htons(port);
  ssock.sin_addr.s_addr = inet_addr(addr);

  res = sendto(sfd, msg, strlen(msg), 0, (struct sockaddr*) &ssock, sizeof(ssock));

  printf ("\n socket %i\n", sfd);
  printf ("\n message %s\n", msg);
  printf ("\n IP : %s\n", addr);
  printf ("\n port %i\n", port);

  if (res < 0)
    {
      perror("sendto error");
      return -1;
    }

  //while (1)
    //    {
      printf ("\n NOTOK\n");
      printf ("\n socket %i\n", sfd);
      printf ("\n buff %s\n", buff);
      printf ("\n IP : %s\n", addr);
      printf ("\n port %i\n", port);

      if ((recvfrom(sfd, buff, BUFFSIZE, 0, (struct sockaddr *) &ssock, &len)) < 0)
	{
	  perror("recvfrom error");
	  return (1);
	}
      printf ("OK : %s\n", buff);
      // }

  return res;
}
